package cn.imvc.app.models;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.puff.cache.redis.Redis;

import cn.imvc.app.domains.OrderState;
import cn.imvc.app.domains.PageDomain;
import cn.imvc.app.entities.Comments;
import cn.imvc.app.entities.GoodsOrder;
import cn.imvc.app.entities.Member;
import cn.imvc.app.repositories.CommentsRepository;
import cn.imvc.core.ICache;
import cn.imvc.util.PageableUtils;
import cn.imvc.util.ToolUtils;

@Service
public class CommentsModelImpl implements CommentsModel {
	@Autowired
	private CommentsRepository commentsRepository;

	@Autowired
	SettingModel settingModel;

	@Autowired
	GoodsOrderModel goodsOrderModel;
	
	@Autowired
	GoodsSkuModel goodsSkuModel;
	@Autowired
	GoodsModel goodsModel;
	@Autowired
	CommonModel commonModel;
	@Autowired
	ICache cache;
	
	@Override
	public Page<Comments> findByGoodsId(Integer goodsId, Integer page,Integer pageSize, String sort)  {
		Integer goodsMaxId = commonModel.findMaxId("goods");
		if (goodsId > goodsMaxId) {
			return null;
		}
		String key = "goodsComments" + goodsId + "_" + page+"_"+pageSize+"_"+sort;
		int minute = ToolUtils.getMinute(new Date());
		PageDomain<Comments> domain = null;
		//cache.remove("DATA", key);
		while (true) {
			domain = cache.get("DATA", key);
			if (domain == null) {
				if (Redis.getInstance().setnx(key + minute, "aa") == 1) {
					Redis.getInstance().expire(key + minute, 20);
					PageRequest pageRequest = PageableUtils.bulidPageRequest(page, pageSize, sort, true);
					Page<Comments> pageResult = commentsRepository.findByGoodsIdAndState(goodsId, (byte) 1, pageRequest);
					domain = new PageDomain<Comments>();
					domain.setPage(pageResult);
					cache.put("DATA", key, domain, 1800);
					Redis.getInstance().remove(key + minute);
					return pageResult;
				} else {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			} else {
				return domain.getPage();
			}
		}
	}

	@Override
	public Page<Comments> findByGoodsSkuId(Integer goodsSkuId, Integer page,Integer pageSize, String sort) {
		PageRequest pageable = PageableUtils.bulidPageRequest(page, pageSize, sort, true);
		return commentsRepository.findByGoodsSkuIdAndState(goodsSkuId, (byte) 1, pageable);
	}

	@Override
	public Map<String, String> upload(MultipartFile[] images, String path) {
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < images.length; i++) {
			Map<String, String> result = settingModel.upload(images[i], path);
			if("0".equals(result.get("code"))){
				map.put("code", "0");
				map.put("msg", "上传失败");
				return map;
			} else if("1".equals(result.get("code"))){
				map.put("image" + i, result.get("fileUrl"));
				map.put("code", "1");
				map.put("msg", "上传成功");
			}
		}
		return map;
	}

	@Override
	public Map<String, String> addComment(Member member, Comments comment, Integer goodsOrderId) {
		Map<String, String> result = new HashMap<String, String>();
		result.put("code", "0");
		if (member == null) {
			result.put("code", "-1");
			result.put("msg", "请登录");
			return result;
		}
		GoodsOrder goodsOrder = goodsOrderModel.findByMemberAndId(member, goodsOrderId);
		if(goodsOrder != null && goodsOrder.getMember().getId() == member.getId()){
			if(goodsOrder.getState() == OrderState.Receipt.getValue() || goodsOrder.getState() == OrderState.SystemReceipt.getValue()
					||goodsOrder.getState() == OrderState.Finish.getValue()||goodsOrder.getState() == OrderState.Commissions.getValue()){
				comment.setMember(member);
				comment.setAddtime(new Date());
				comment.setGoods(goodsOrder.getGoods());
				comment.setGoodsOrder(goodsOrder);
				comment.setGoodsSku(goodsOrder.getGoodsSku());
				comment.setGoodsName(goodsOrder.getGoods().getName());
				comment.setGoodsPrice(goodsOrder.getPrice());
				comment.setGoodsNum(goodsOrder.getNum());
				comment.setGoodsSpec(goodsOrder.getSpec());
				comment.setState((byte)0);
				comment = save(comment);
				goodsOrder.setCommentState(OrderState.Comments.getValue());
				goodsOrder.setUpdatedAt(new Date());
				goodsOrderModel.save(goodsOrder);
//				goodsModel.retrySaveGoods(goodsOrder.getGoods().getId(), 0, 0, 0, 1);;
//				goodsSkuModel.retryMaintainCountsOfGoodsSku(goodsOrder.getGoodsSku().getId(), 0, 0, 0, 1);
				result.put("code", "1");
				result.put("msg", "评论成功");
			} else {
				result.put("code", "1");
				result.put("msg", "您没有权限操作");
			}
		} else {
			result.put("code", "1");
			result.put("msg", "您没有权限操作");
		}
		return result;
	}

	public Comments save(Comments comment) {
		return commentsRepository.saveAndFlush(comment);
	}

}
